import { useRef, useState } from 'react';
import { Space, App, Button, Typography } from 'antd';
import { useBoolean } from 'ahooks';
import { cloneDeep } from 'lodash-es';
import Table from 'src/components/Table';
import PermissionButton from 'src/components/Permission';
import { getMenuTree, DeleteMenu } from 'src/api/modules/system';
import { IMenuRespData, IMenuRespFlatData } from 'src/interface';
import { schema, columns } from './data';
import MenuModal from './MenuModal';

const Link = Typography.Link;

export default function MenuManage() {
  const { message, modal } = App.useApp();
  const [visible, { setTrue, setFalse }] = useBoolean(false);
  const [currentMenuInfo, setCurrentMenuInfo] = useState<IMenuRespFlatData | null>(null);
  const TableRef = useRef<{ onRefresh: () => void; data: any[] }>({
    onRefresh: () => {},
    data: [],
  });
  const requestAfterFilter = (data: IMenuRespData[]): IMenuRespFlatData[] => {
    return data.map((item) => {
      const data = {
        ...item,
        ...(item.meta ?? {}),
      };
      delete data.meta;
      if (item.children && item.children.length > 0) {
        data.children = requestAfterFilter(item.children);
      }
      return data;
    });
  };

  const onDelete = async (id: string) => {
    modal.confirm({
      title: '删除',
      content: '注意删除后将无法恢复',
      async onOk() {
        try {
          await DeleteMenu(id);
          message.success('删除成功');
          TableRef.current.onRefresh();
        } catch (err) {
          console.log(err);
        }
      },
      onCancel() {},
    });
  };

  const addMenusHandle = () => {
    setCurrentMenuInfo(null);
    setTrue();
  };

  const editMenusHandle = (row: IMenuRespFlatData) => {
    const data = cloneDeep(row);
    delete data.children;
    setCurrentMenuInfo(data);
    setTrue();
  };

  return (
    <div className="m-[16px] rounded-md min-[calc(100vh - 32px)]">
      <Table
        ref={TableRef}
        downloadName="菜单管理"
        columns={[
          ...columns,
          {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            width: 100,
            align: 'center',
            fixed: 'right',
            render: (_text: string, record: IMenuRespData) => {
              return (
                <Space size={'small'}>
                  <Link onClick={() => editMenusHandle(record)}>编辑</Link>
                  <PermissionButton
                    permission="SYSTEM_MENU_DELETE"
                    type="link"
                    onClick={() => onDelete(record.menuId)}>
                    删除
                  </PermissionButton>
                </Space>
              );
            },
          },
        ]}
        formProps={{ schemas: schema }}
        request={getMenuTree}
        rowKey="menuId"
        requestAfterFilter={requestAfterFilter}
        left={
          <Button type="primary" onClick={addMenusHandle}>
            新增菜单
          </Button>
        }
      />
      <MenuModal
        menuList={TableRef.current.data}
        open={visible}
        data={currentMenuInfo}
        maskClosable={false}
        onCancel={setFalse}
        onOk={() => TableRef.current.onRefresh()}></MenuModal>
    </div>
  );
}
